<?php

namespace app\common\model;

use app\model\Agent;
use app\model\AgentBalanceLog;
use app\model\GoodsNotify;
use app\model\CouponOrder;
use think\facade\Db;

class Goods
{
    //  protected static $appId="20211617890705";
    //  protected static $apikey="DECF8917D1E27A610C67D3833FCC9DA2";
    protected static $appId = "20221642092167";
    protected static $apikey = "D42E15F4A31BE394C10C6D14E9F25D28";

    /**
     * 视频充值接口
     *  acount 充值账户  num 购买数量
     **/
    public static function addVideo($skuId, $orderId, $account, $num)
    {
        $data['APIID'] = self::$appId;
        $data['Account'] = $account;
        $data['BuyNum'] = 1;
        $data['CreateTime'] = date("YmdHis");
        $data['IsCallBack'] = 1;
        $data['OrderID'] = $orderId;
        $data['ProductCode'] = $skuId;
        $sign = $data;
        $sign['APIKEY'] = self::$apikey;
        $sign = strtoupper(md5(http_build_query($sign)));
        $data['Sign'] = $sign;
        $data['CallBack'] = "http://hfcs.dmjvip.com/api/notifyV2/coupon";
        $result = curlPost("http://open.jiaofei100.com/Api/PayVideo.aspx", $data);
        GoodsNotify::addGoods($result, $data, $orderId);
        return $result;
    }

    /**
     *  游戏/卡密/卡券 充值接口
     *  tradeType 商品类型
     */
    public static function addCard($tradeType, $account, $marketPrice, $num, $orderId, $goodId, $ip)
    {
        $data['APIID'] = self::$appId;
        $data['Account'] = $account;
        $data['BuyNum'] = 1;
        $data['ClientIP'] = $ip;
        $data['CreateTime'] = date("YmdHis");
        $data['GoodsID'] = $goodId;
        $data['isCallBack'] = 1;
        $data['OrderID'] = $orderId;
        $data['TotalPrice'] = $marketPrice * 10;
        $data['TradeType'] = $tradeType;
        $data['UnitPrice'] = $marketPrice * 10;
        $sign = $data;
        $sign['APIKEY'] = self::$apikey;
        $sign = strtoupper(md5(http_build_query($sign)));
        $data['Sign'] = $sign;
        $data['CallBack'] = "http://hfcs.dmjvip.com/api/notifyV2/coupon";
        $result = curlPost("http://open.jiaofei100.com/Api/PayGame.aspx", $data);
        GoodsNotify::addGoods($result, $data, $orderId);
        return $result;
    }

    /**
     * 权益订单回调通知
     * @param $orderObj  权益订单  传的是 模型对象
     * @param $update  需要更新的数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function handleNotify($orderObj, $update)
    {
        $orderId = $orderObj->id;

        if (empty($update['complete_at'])) {
            $update['complete_at'] = date('Y-m-d H:i:s');
        }

        // 订单充值失败  进入到待退款队列
        if (CouponOrder::C_STATUS_RECHARGE_FAIL == $update['status']) {
            $update['refund_status'] = CouponOrder::C_REFUND_STATUS_ING;
        }

        // 充值成功
        if (CouponOrder::C_STATUS_RECHARGE_SUCCESS == $update['status']) {
            if (SETTLE_TYPE_PROFIT == $orderObj->settle_type) {
                $profit_balance = Agent::where(['id' => $orderObj->agent_id])->value('profit_balance');
                // 充值成功返佣金
                Db::name('agent')
                    ->where('id', $orderObj->agent_id)
                    ->inc('profit_balance', $orderObj->profit)
                    ->inc('total_profit', $orderObj->profit)
                    ->update([
                        'balance_last_updated_at' => date('Y-m-d H:i:s'),
                    ]);

                $agentBalanceLog = new AgentBalanceLog();
                $logData = [
                    'agent_id' => $orderObj->agent_id,
                    'type' => BALANCE_COUPON_COMMISS,
                    'amount' => $orderObj->profit,
                    'old_balance' => $profit_balance,
                    'new_balance' => $profit_balance + $orderObj->profit,
                    'remark' => '权益订单完成返佣：' . fen2yuan($orderObj->profit) . '元。订单号：' . $orderObj->order_id,
                    'quote_id' => $orderObj->id,
                    'trade_no' => $orderObj->order_id,
                ];
                $agentBalanceLog->save($logData);

                $update['settled_at'] = date('Y-m-d H:i:s');
                $update['agent_settle_status'] = 3;
            }

            // 成功了，插入财务明细
            FinanceStat::addSuccessRecord([
                'order_id' => $orderObj->order_id,
                'order_type' => PRODUCT_COUPON_SERV,
                'settle_type' => $orderObj->settle_type,
                'amount' => $orderObj->amount,
                'sale_price' => $orderObj->amount,
                'settle_price' => $orderObj->settle_price,
                'supplier_price' => $orderObj->supplier_price,
                'profit' => $orderObj->profit,
                'platform_profit' => $orderObj->platform_profit,
                'supplier_id' => $orderObj->supplier_id,
                'agent_id' => $orderObj->agent_id,
                'remark' => '充值成功',
            ]);
        }

        // 保存订单数据
        // CouponOrder::update($update, ['id' => $orderId]);
        return Db::name('coupon_order')
            ->where('id', $orderId)
            ->where('status', CouponOrder::C_STATUS_SUBMIT)
            ->update($update);
    }
}
